package org.jeecg.modules.inspect.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inspect.entity.InsRule;
import org.jeecg.modules.inspect.entity.InsRuleDuty;
import org.jeecg.modules.inspect.entity.InsRuleLine;
import org.jeecg.modules.inspect.service.IInsRuleDutyService;
import org.jeecg.modules.inspect.service.IInsRuleLineService;
import org.jeecg.modules.inspect.service.IInsRuleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 配置规则
 * @Author: jeecg-boot
 * @Date:   2023-11-24
 * @Version: V1.0
 */
@Api(tags="配置规则")
@RestController
@RequestMapping("/inspect/insRule")
@Slf4j
public class InsRuleController extends JeecgController<InsRule, IInsRuleService> {

	@Autowired
	private IInsRuleService insRuleService;

	@Autowired
	private IInsRuleLineService insRuleLineService;

	@Autowired
	private IInsRuleDutyService insRuleDutyService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param insRule
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "配置规则-分页列表查询")
	@ApiOperation(value="配置规则-分页列表查询", notes="配置规则-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<InsRule>> queryPageList(InsRule insRule,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InsRule> queryWrapper = QueryGenerator.initQueryWrapper(insRule, req.getParameterMap());
		Page<InsRule> page = new Page<InsRule>(pageNo, pageSize);
		IPage<InsRule> pageList = insRuleService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param insRule
     * @return
     */
    @AutoLog(value = "配置规则-添加")
    @ApiOperation(value="配置规则-添加", notes="配置规则-添加")
    //@RequiresPermissions("org.jeecg.modules:ins_rule:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody InsRule insRule) {
		if(insRule.getRuleType().equals("2")) {
			insRule.setExecuteCycle("6");
		}
        insRuleService.save(insRule);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param insRule
     * @return
     */
    @AutoLog(value = "配置规则-编辑")
    @ApiOperation(value="配置规则-编辑", notes="配置规则-编辑")
    //@RequiresPermissions("org.jeecg.modules:ins_rule:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody InsRule insRule) {
		if(insRule.getRuleType().equals("2")) {
			insRule.setExecuteCycle("6");
		}
        insRuleService.updateById(insRule);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "配置规则-通过id删除")
    @ApiOperation(value="配置规则-通过id删除", notes="配置规则-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:ins_rule:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        insRuleService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "配置规则-批量删除")
    @ApiOperation(value="配置规则-批量删除", notes="配置规则-批量删除")
    //@RequiresPermissions("org.jeecg.modules:ins_rule:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.insRuleService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_rule:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InsRule insRule) {
        return super.exportXls(request, insRule, InsRule.class, "配置规则");
    }

    /**
     * 导入
     * @return
     */
    //@RequiresPermissions("org.jeecg.modules:ins_rule:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InsRule.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-线路规则-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "线路规则-通过主表ID查询")
	@ApiOperation(value="线路规则-通过主表ID查询", notes="线路规则-通过主表ID查询")
	@GetMapping(value = "/listInsRuleLineByMainId")
    public Result<IPage<InsRuleLine>> listInsRuleLineByMainId(InsRuleLine insRuleLine,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<InsRuleLine> queryWrapper = QueryGenerator.initQueryWrapper(insRuleLine, req.getParameterMap());
        Page<InsRuleLine> page = new Page<InsRuleLine>(pageNo, pageSize);
        IPage<InsRuleLine> pageList = insRuleLineService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param insRuleLine
	 * @return
	 */
	@AutoLog(value = "线路规则-添加")
	@ApiOperation(value="线路规则-添加", notes="线路规则-添加")
	@PostMapping(value = "/addInsRuleLine")
	public Result<String> addInsRuleLine(@RequestBody InsRuleLine insRuleLine) {
		List<InsRuleLine> list = insRuleLineService.list(Wrappers.<InsRuleLine>lambdaQuery()
				.eq(InsRuleLine::getRuleId, insRuleLine.getRuleId())
				.eq(InsRuleLine::getLineId, insRuleLine.getLineId()));

		if(CollUtil.isNotEmpty(list)) {
			return Result.error("该线路已存在！");
		}
		insRuleLineService.save(insRuleLine);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param insRuleLine
	 * @return
	 */
	@AutoLog(value = "线路规则-编辑")
	@ApiOperation(value="线路规则-编辑", notes="线路规则-编辑")
	@RequestMapping(value = "/editInsRuleLine", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editInsRuleLine(@RequestBody InsRuleLine insRuleLine) {
		InsRuleLine oldRuleLine = insRuleLineService.getById(insRuleLine.getId());

		if(!oldRuleLine.getLineId().equals(insRuleLine.getLineId())) {
			List<InsRuleLine> list = insRuleLineService.list(Wrappers.<InsRuleLine>lambdaQuery()
					.eq(InsRuleLine::getRuleId, insRuleLine.getRuleId())
					.eq(InsRuleLine::getLineId, insRuleLine.getLineId()));

			if(CollUtil.isNotEmpty(list)) {
				return Result.error("该线路已存在！");
			}
		}
		insRuleLineService.updateById(insRuleLine);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "线路规则-通过id删除")
	@ApiOperation(value="线路规则-通过id删除", notes="线路规则-通过id删除")
	@DeleteMapping(value = "/deleteInsRuleLine")
	public Result<String> deleteInsRuleLine(@RequestParam(name="id",required=true) String id) {
		insRuleLineService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "线路规则-批量删除")
	@ApiOperation(value="线路规则-批量删除", notes="线路规则-批量删除")
	@DeleteMapping(value = "/deleteBatchInsRuleLine")
	public Result<String> deleteBatchInsRuleLine(@RequestParam(name="ids",required=true) String ids) {
	    this.insRuleLineService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportInsRuleLine")
    public ModelAndView exportInsRuleLine(HttpServletRequest request, InsRuleLine insRuleLine) {
		 // Step.1 组装查询条件
		 QueryWrapper<InsRuleLine> queryWrapper = QueryGenerator.initQueryWrapper(insRuleLine, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InsRuleLine> pageList = insRuleLineService.list(queryWrapper);
		 List<InsRuleLine> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "线路规则");
		 mv.addObject(NormalExcelConstants.CLASS, InsRuleLine.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("线路规则报表", "导出人:" + sysUser.getRealname(), "线路规则"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importInsRuleLine/{mainId}")
    public Result<?> importInsRuleLine(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InsRuleLine> list = ExcelImportUtil.importExcel(file.getInputStream(), InsRuleLine.class, params);
				 for (InsRuleLine temp : list) {
                    temp.setRuleId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 insRuleLineService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-线路规则-end----------------------------------------------*/

    /*--------------------------------子表处理-值班规则-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "值班规则-通过主表ID查询")
	@ApiOperation(value="值班规则-通过主表ID查询", notes="值班规则-通过主表ID查询")
	@GetMapping(value = "/listInsRuleDutyByMainId")
    public Result<IPage<InsRuleDuty>> listInsRuleDutyByMainId(InsRuleDuty insRuleDuty,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<InsRuleDuty> queryWrapper = QueryGenerator.initQueryWrapper(insRuleDuty, req.getParameterMap());
        Page<InsRuleDuty> page = new Page<InsRuleDuty>(pageNo, pageSize);
        IPage<InsRuleDuty> pageList = insRuleDutyService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param insRuleDuty
	 * @return
	 */
	@AutoLog(value = "值班规则-添加")
	@ApiOperation(value="值班规则-添加", notes="值班规则-添加")
	@PostMapping(value = "/addInsRuleDuty")
	public Result<String> addInsRuleDuty(@RequestBody InsRuleDuty insRuleDuty) {
		insRuleDutyService.save(insRuleDuty);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param insRuleDuty
	 * @return
	 */
	@AutoLog(value = "值班规则-编辑")
	@ApiOperation(value="值班规则-编辑", notes="值班规则-编辑")
	@RequestMapping(value = "/editInsRuleDuty", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editInsRuleDuty(@RequestBody InsRuleDuty insRuleDuty) {
		insRuleDutyService.updateById(insRuleDuty);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "值班规则-通过id删除")
	@ApiOperation(value="值班规则-通过id删除", notes="值班规则-通过id删除")
	@DeleteMapping(value = "/deleteInsRuleDuty")
	public Result<String> deleteInsRuleDuty(@RequestParam(name="id",required=true) String id) {
		insRuleDutyService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "值班规则-批量删除")
	@ApiOperation(value="值班规则-批量删除", notes="值班规则-批量删除")
	@DeleteMapping(value = "/deleteBatchInsRuleDuty")
	public Result<String> deleteBatchInsRuleDuty(@RequestParam(name="ids",required=true) String ids) {
	    this.insRuleDutyService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportInsRuleDuty")
    public ModelAndView exportInsRuleDuty(HttpServletRequest request, InsRuleDuty insRuleDuty) {
		 // Step.1 组装查询条件
		 QueryWrapper<InsRuleDuty> queryWrapper = QueryGenerator.initQueryWrapper(insRuleDuty, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<InsRuleDuty> pageList = insRuleDutyService.list(queryWrapper);
		 List<InsRuleDuty> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "值班规则");
		 mv.addObject(NormalExcelConstants.CLASS, InsRuleDuty.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("值班规则报表", "导出人:" + sysUser.getRealname(), "值班规则"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importInsRuleDuty/{mainId}")
    public Result<?> importInsRuleDuty(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<InsRuleDuty> list = ExcelImportUtil.importExcel(file.getInputStream(), InsRuleDuty.class, params);
				 for (InsRuleDuty temp : list) {
                    temp.setRuleId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 insRuleDutyService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-值班规则-end----------------------------------------------*/




}
